import { useDict } from '@/utils/dict'
import { getDicts } from '@/api/system/dict/data'
import store from '@/store'
import { useStore } from 'vuex'

function searchDictByKey(dict: Record<string, any>, key: string): any {
  if (key == null && key == '') {
    return null
  }
  try {
    for (let i = 0; i < Object.keys(dict).length; i++) {
      if (Object.keys(dict)[i] == key) {
        return Object.values(dict)[i]
      }
    }
  } catch (e) {
    return null
  }
}

export default function install() {
  useDict({
    metas: {
      '*': {
        labelField: 'dictLabel',
        valueField: 'dictValue',
        request(dictMeta: any) {
          const dictStore = useStore()
          const storeDict = searchDictByKey(dictStore.state.dict, dictMeta.type)
          if (storeDict) {
            return new Promise((resolve) => {
              resolve(storeDict)
            })
          } else {
            return new Promise((resolve, reject) => {
              getDicts(dictMeta.type)
                .then((res: any) => {
                  // dictStore.setDict({ key: dictMeta.type, value: res.data })
                  store.dispatch('dict/setDict', { key: dictMeta.type, value: res.data })
                  resolve(res.data)
                })
                .catch((error: any) => {
                  reject(error)
                })
            })
          }
        },
      },
    },
  })
}
